import { Component, OnInit } from '@angular/core';
import { appService } from '../../../../my-service/app.service';
import { fadeIn } from '../../../../animate';
import { canvasmsg } from '../canvasmsg';
import { classService } from '../../../../my-service/class.service'
import { UtilService } from '../../../../my-service/util.service'

@Component({
  selector: 'timelist-root',
  templateUrl: './timelist.component.html',
  styleUrls: ['./timelist.component.css'],
  animations: [fadeIn]
})
export class timelistComponent implements OnInit{
  FK_CreatorGuid;
  FK_CanvasGuid;
  img;
  constructor(private appservice: appService, private classService: classService, private utilService: UtilService) {
    this.FK_CanvasGuid=this.utilService.canvas().guid
    this.img=this.utilService.canvas().img
   }
  trainlist = []
  load = false;
  timeline = false;
  recoveryshow = false;
  canvasmsg: canvasmsg = {
    BackGroundImg: '',
    Canvaschoose: "每组或每人一张",
    Description: '加载中',
    Developer: "舟道科技",
    ID: 0,
    Imgurl: '',
    Logo: '',
    MainRatio: 0.517,
    Name: '加载中',
    PK_CanvasGuid: '',
    Packetmode: '个人或分组',
    SmallImgurl: '',
    Status: 1,
    Type: '',
    Updatetime: '',
    Usages: '',
    Usagescenario: "任何场景",
    Versions: '1.0',
    EnglishName: ''
  };
  addwindow = false;
  editwindow = false;
  form = {
    Title: '',
    Description: '',
    Password: '00000',
    FK_ClassGuid: '000000',
    class: '匿名模式',
    PK_TrainningGuid: ''
  }
  selectbox = false;
  classlist = [];
  usermsg = {
    Answer: '',
    Cover: '',
    Description: '',
    Email: '',
    FK_OccupationGuid: '',
    FK_ProblemGuid: '',
    Idiograph: '',
    Name: '',
    PK_OrgGuid: '',
    PK_UserGuid: '',
    Phone: '',
    Sex: '',
    UserName: '',
    content: '',
    occupation: '',
    orgName: ''
  };
  noclass = false;
  ngOnInit() {
    this.utilService.getUserInfo().then(re => {
      this.FK_CreatorGuid = re.userGuid
      this.form.Password = this.getCode(5)
      this.appservice.lpplist({
        FK_CanvasGuid: this.FK_CanvasGuid,
        FK_CreatorGuid: this.FK_CreatorGuid,
        Status: 1
      }).then((re2) => {
        this.trainlist = re2;
      }).then(() => {
        this.load = true;
      })
      this.appservice.getcanvas(this.FK_CanvasGuid).then(re => {
        this.canvasmsg = re;
        this.form.Title = `${this.canvasmsg.Name}${this.getDate()}`;
      })
      this.appservice.getThisUser(this.FK_CreatorGuid).then(re => {
        if (re.status) {
          this.usermsg = re.data;
          this.form.Description = re.data.UserName + '创建的训练';
        }
      })
      this.classService.ClassForUser(this.FK_CreatorGuid).then(re => {
        let data = [];
        data.push(
          {
            ClassName: '匿名模式',
            PK_ClassGuid: '000000'
          }
        )
        for (let i = 0; i < re.data.length; i++) {
          data.push(re.data[i])
        }
        if (re.length == 0) {
          this.noclass = true;
        }

        this.classlist = data;
      })
    })
  }
  addform() {
    if (this.form.Title == '') {
      this.utilService.remind('error', '名字不能为空!')
      return
    }
    if (this.form.Password == '') {
      this.utilService.remind('error', '邀请码不能为空!')
      return
    }
    if (this.form.Password.length != 5) {
      this.utilService.remind('error', '请输入五位邀请码!')
      return
    }
    let data = {
      FK_CanvasGuid:'',
      Title: '',
      Description: '',
      CreaterGuid: '',
      CreaterName: '',
      CreaterOrgName:'',
      Password: '',
      FK_ClassGuid: ''
    }
    data = {
      FK_CanvasGuid: this.FK_CanvasGuid,//canvas的guid（创建的是哪种画布）
      Title: this.form.Title,//训练名称
      Description: this.form.Description,//描述
      CreaterGuid: this.FK_CreatorGuid,//创建人guid
      CreaterName: this.usermsg.UserName,//创建人的名字
      CreaterOrgName: this.usermsg.orgName,//创建人的机构
      Password: this.form.Password,//五位数字
      FK_ClassGuid: this.form.FK_ClassGuid//班级guid（如果是匿名模式，则传'000000'）
    }
    this.appservice.postcanvastrain(data).then(re => {
      if (re.status == 1) {
        this.addwindow = false;
        this.initialize();
        console.log(this.utilService.canvas().projectName)
        let apiConfig={
          projectName:this.utilService.canvas().projectName,
          guid:re.PK_TrainningGuid,
          endTime: this.utilService.timestamp(new Date())+2592000,
          FK_ClassGuid:data.FK_ClassGuid.length>10?data.FK_ClassGuid:null,
          FK_UserGuid:this.FK_CreatorGuid
        }
        this.utilService.createCode(apiConfig).then(rec=>{
          this.appservice.bindCode(re.PK_TrainningGuid,rec.code).then((re6)=>{
            this.appservice.lpplist({
              FK_CanvasGuid: this.FK_CanvasGuid,
              FK_CreatorGuid: this.FK_CreatorGuid,
              Status: 1
            }).then((re2) => {
              this.trainlist = re2;
            })
          })
        })
      }
      else { this.utilService.remind('error', '创建失败，请刷新，稍后重试！') }
    })
  }
  initialize() {
    this.form = {
      Title: `${this.canvasmsg.Name}${this.getDate()}`,
      Description: this.usermsg.UserName + '创建的训练',
      Password: this.getCode(5),
      FK_ClassGuid: '000000',
      class: '匿名模式',
      PK_TrainningGuid: ''
    }
  }
  editform(item) {
    let _class = '匿名模式';
    this.classlist.forEach(el => {
      if (el.PK_ClassGuid == item.FK_ClassGuid) {
        _class = el.ClassName
      }
    });
    this.form = {
      Title: item.Title,
      Description: item.Description,
      Password: item.Password,
      FK_ClassGuid: item.FK_ClassGuid,
      class: _class,
      PK_TrainningGuid: item.PK_TrainningGuid
    }
    this.editwindow = true;
  }
  change($event) {
    this.timeline = !this.timeline
  }
  del($event) {
    this.appservice.lpplist({
      FK_CanvasGuid: this.FK_CanvasGuid,
      FK_CreatorGuid: this.FK_CreatorGuid,
      Status: 1
    }).then((re2) => {
      this.trainlist = re2;
    })
    this.recoveryshow = false;
  }
  huifu($event) {
    this.appservice.lpplist({
      FK_CanvasGuid: this.FK_CanvasGuid,
      FK_CreatorGuid: this.FK_CreatorGuid,
      Status: 1
    }).then((re2) => {
      this.trainlist = re2;
    })
  }
  getDate() {
    let date = new Date(); //取当前时间
    let month = date.getMonth() + 1;
    let months, strDates;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      months = "0" + month;
    }else{
      months=`${month}`
    }
    if (strDate >= 0 && strDate <= 9) {
      strDates = "0" + strDate;
    } else {
      strDates = strDate
    }
    let currentdate = date.getFullYear() + months + strDates;

    return currentdate;
  }
  getCode(num) {
    let id = "";
    for (let i = 1; i <= num; i++) {
      let n = Math.floor(Math.random() * 10.0).toString(10);
      id += n;

    }
    return id;
  }
  shuiji() {
    this.form.Password = this.getCode(5);
  }
  select(item) {
    this.form.FK_ClassGuid = item.PK_ClassGuid;
    this.form.class = item.ClassName;
    this.selectbox = false;
  }
  checknum(num, item) {
    if (item == 'Password') {
      if (JSON.stringify(this.form[item]).length > num) {
        this.form[item] = parseInt(JSON.stringify(this.form[item]).slice(0, num))
      }
    } else {
      if (this.form[item].length > num) {
        this.form[item] = this.form[item].slice(0, num)
      }
    }
  }
  edit() {
    this.utilService.comfirm('确定要修改该训练吗？', () => {
      if (this.form.Title == '') {
        this.utilService.remind('error', '名字不能为空!')
        return
      }
      if (this.form.Password == '') {
        this.utilService.remind('error', '邀请码不能为空!')
        return
      }
      if (this.form.Password.length != 5) {
        this.utilService.remind('error', '请输入五位邀请码!')
        return
      }
      let data = {}
      data = {
        Title: this.form.Title,//训练名字
        Description: this.form.Description,//训练描述
        Password: this.form.Password,//密码
        FK_ClassGuid: this.form.FK_ClassGuid,//班级guid（如果是匿名模式，则传'000000'）
        PK_TrainningGuid: this.form.PK_TrainningGuid//训练guid
      }
      this.appservice.edittrain(data).then(re => {
        if (re.status == 1) {
          this.editwindow = false;
          this.initialize();
          this.appservice.lpplist({
            FK_CanvasGuid: this.FK_CanvasGuid,
            FK_CreatorGuid: this.FK_CreatorGuid,
            Status: 1
          }).then((re2) => {
            this.trainlist = re2;
          })
        } else {
          this.utilService.remind('error', '创建失败，请刷新，稍后重试！')
        }
      })
    })
  }
}
